package com.cuitrip.business.tripservice;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cuitrip.apiservice.TrackBusiness;
import com.cuitrip.app.MainApplication;
import com.cuitrip.business.comment.ReviewInfo;
import com.cuitrip.business.comment.ViewReviewsActivity;
import com.cuitrip.business.home.favorite.proxy.FavProxy;
import com.cuitrip.business.home.favorite.ui.FavAnimation;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.proxy.LoginProxy;
import com.cuitrip.business.share.ShareChannelBuilder;
import com.cuitrip.business.share.model.ServiceShareObject;
import com.cuitrip.business.share.ui.ShareDialogFragment;
import com.cuitrip.business.track.TrackProxy;
import com.cuitrip.business.tripservice.model.FavInfo;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.presenter.TripDetailPresenter;
import com.cuitrip.business.tripservice.proxy.PriceProxy;
import com.cuitrip.business.tripservice.ui.CircleLogoHolderView;
import com.cuitrip.business.tripservice.ui.TripDetailView;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.user.proxy.UserInfoProxy;
import com.cuitrip.component.Label;
import com.cuitrip.component.LabelView;
import com.cuitrip.component.RatingBarView;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.component.para.ParaListView;
import com.cuitrip.component.para.model.Para;
import com.cuitrip.component.para.proxy.ParaProxy;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.resource.DrawableClass;
import com.cuitrip.resource.ResourceManager;
import com.cuitrip.service.R;
import com.cuitrip.util.I118Util;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.text.TextProxy;
import com.cuitrip.util.time.InputTime;
import com.cuitrip.util.time.OutputTime;
import com.cuitrip.util.time.TimeUtil;
import com.cuitrip.util.track.TrackUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.ecommerce.Product;
import com.google.android.gms.analytics.ecommerce.ProductAction;
import com.lab.adapter.BasePageAdapter;
import com.lab.adapter.HolderViewAdapter;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.component.list.LinearListView;
import com.lab.image.process.MakeImageUtil;
import com.lab.jumper.Jumper;
import com.lab.utils.ArrayUtil;
import com.lab.utils.ImageHelper;
import com.lab.utils.NumberUtils;
import com.lab.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class ServiceDetailActivity extends CustomUiFragmentActivity implements TripDetailView {
    public static final String SERVICE_ID = "service_id";
    public static final String USER_TYPE = "user_type";
    public static final String CHECK_STATUS = "check_status";

    public static final String MODE_KEY = "mode_key";

    public static final int DEFAULT = 0x00;
    public static final int SNAPSHOT = 0x01;
    public static final int FINDER_MODE = 0x02;

    private int mode = DEFAULT;


    private TripDetailPresenter mTripDetailPresenter;

    private String mServiceId;
    @Bind(R.id.state_layout)
    StateLayout mStateLayout;


    @Bind(R.id.like_img)
    ImageView favTextView;

    @Bind(R.id.service_tag)
    TextView serviceTagTextView;

    @Bind(R.id.highlight_list)
    ParaListView mHighLightListView;

    @Bind(R.id.pay_include_list)
    ParaListView mPayIncludeListView;

    @Bind(R.id.pay_exclude_list)
    ParaListView mPayExcludeListView;

    @Bind(R.id.duration_layout)
    ItemLayout mDurationLayout;

    @Bind(R.id.num_layout)
    ItemLayout numLayout;

    @Bind(R.id.pre_order_layout)
    ItemLayout mPreOrderLayout;

    @Bind(R.id.other_layout)
    ItemLayout mOtherInstructionLayout;

    @Bind(R.id.last_comment_author_img)
    CircleImageView mLastReviewerLogo;

    @Bind(R.id.insider_register_layout)
    ItemLayout mRegisterLayout;

    @Bind(R.id.insider_identification_layout)
    ItemLayout mIdentificationLayout;

    @Bind(R.id.insider_interest_list)
    ParaListView mInterestListView;

    @Bind(R.id.insider_language_list)
    ParaListView mLanguageListView;

    @Bind(R.id.date_layout)
    ItemLayout mDateLayout;

    @Bind(R.id.fav_layout)
    View favLayout;

    @Bind(R.id.fav_count)
    TextView mFavCountView;

    @Bind(R.id.fav_list)
    LinearListView favListView;

    @Bind(R.id.ct_book)
    TextView bookView;

    @Bind(R.id.insider_block)
    View insiderBlockView;

    @Bind(R.id.service_pic)
    ViewPager mViewPager;

    @Bind(R.id.verifiedView)
    ImageView verifiedView;


    private ShareDialogFragment shareDialogFragment;

    HolderViewAdapter favListViewAdapter;

    private FavAnimation mFavAnimation;
    private String languages;

    private int checkStatus = ServiceInfo.STATUS_CHECHED;

    private String subInfoAddress;

    public static void start(Context context, String serviceId) {
        start(context, serviceId, DEFAULT, ServiceInfo.STATUS_CHECHED);
    }

    public static void start(Context context, String serviceId, int mode) {
        start(context, serviceId, mode, ServiceInfo.STATUS_CHECHED);
    }

    public static void startFinder(Context context, String serviceId, int checkStatus) {
        start(context, serviceId, FINDER_MODE, checkStatus);
    }

    public static void start(Context context, String serviceId, int mode, int checkStatus) {
        Jumper.launchActivity(context, new Intent(context, ServiceDetailActivity.class)
                .putExtra(SERVICE_ID, serviceId)
                .putExtra(MODE_KEY, mode)
                .putExtra(CHECK_STATUS, checkStatus));
    }

    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent == null) {
            finish();
            return;
        }

        String id = intent.getStringExtra(SERVICE_ID);

        checkStatus = intent.getIntExtra(CHECK_STATUS, ServiceInfo.STATUS_CHECHED);

        mServiceId = id;
        if (getIntent().hasExtra(MODE_KEY)) {
            mode = getIntent().getIntExtra(MODE_KEY, DEFAULT);
        }
        mTripDetailPresenter = new TripDetailPresenter();
        mTripDetailPresenter.attachView(this);
        super.onCreate(savedInstanceState, R.layout.ct_activity_service_detail);

        TrackUtil.trackScreenName("/service/detail");
        TrackProxy.getInstance().reviewPage(TrackBusiness.Source.SERVICE_DETAIL, mServiceId);
    }


    protected void onDestroy() {
        super.onDestroy();
        mTripDetailPresenter.detachView();
        if (mFavAnimation != null) {
            mFavAnimation.detach();
        }
    }


    public void initView() {
        ButterKnife.bind(this);
        if (TextUtils.isEmpty(mServiceId)) {
            finish();
            return;
        }
        if (mode == FINDER_MODE) {
            bookView.setVisibility(View.GONE);
            favTextView.setVisibility(View.GONE);
        } else {
            favTextView.setVisibility(View.VISIBLE);
            bookView.setVisibility(View.VISIBLE);
        }
        if (mode == SNAPSHOT) {
            bookView.setVisibility(View.GONE);
            favTextView.setVisibility(View.GONE);
            mTopbarRightArea.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.like_img)
    public void toggleFavTrip() {
        mTripDetailPresenter.toggleFavoriteService();
    }

    @Override
    public void initListener() {
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                initData();
            }
        });
    }

    @Override
    public void initData() {
        mStateLayout.changeState(StateLayout.State.Loading);
        mTripDetailPresenter.loadServiceDetail(mServiceId, checkStatus, mode);
    }


    private void bindParaItem(ParaListView paraListView, String paraOutput, boolean emptyIsGone) {
        if (!TextUtils.isEmpty(paraOutput)) {
            List<Para> paraList = new ArrayList<>();
            ArrayList<CharSequence> charSequenceList = ParaProxy.getInstance().getParaList(paraOutput);
            for (CharSequence charSequence : charSequenceList) {
                if (TextUtils.isEmpty(charSequence)) {
                    continue;
                }
                paraList.add(new Para(charSequence));
            }
            paraListView.setParas(paraList);
        } else {
            if (!emptyIsGone) {
                List<Para> paraList = new ArrayList<>();
                paraList.add(new Para(ResourceUtil.getString(R.string.value_no_set)));
                paraListView.setParas(paraList);
            }
        }
    }

    BasePageAdapter mAdapter = new BasePageAdapter<String>() {


        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        public Object instantiateItem(ViewGroup container, int position) {
            ImageView view = new ImageView(ServiceDetailActivity.this);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ImageHelper.displayCtImage(mData != null ? mData.get(position) : null, view, null);
            container.addView(view);
            return view;
        }

        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    };


    @OnClick(R.id.comment_click)
    protected void moreComment() {
        startActivity(new Intent(this, ViewReviewsActivity.class).putExtra(SERVICE_ID, mServiceId));
    }

    @OnClick(R.id.ct_book)
    protected void bookAction() {
        if (LoginInstance.isLogin()) {
            //gotoOrder();
            mTripDetailPresenter.judgeBasicUserInfo();
        } else {
            LoginProxy.getInstance().gotoUserEnter(ServiceDetailActivity.this);
        }
    }

    @OnClick(R.id.author_img)
    protected void authorMore() {
        mTripDetailPresenter.navigateInsiderPage();
    }

    @OnClick(R.id.service_click)
    protected void gotoServiceDescription() {
        mTripDetailPresenter.navigateDescriptionPage();
    }

    protected void onLoginSuccess() {
        gotoOrder();
    }

    private void gotoOrder() {
        mTripDetailPresenter.navigateOrderPage();
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }

    @Override
    public void onTopbarRightPress() {
        if (mode == FINDER_MODE) {
            if (checkStatus == ServiceInfo.STATUS_CHECHED) {
                mTripDetailPresenter.navigateEditPage();
            }
        } else {
            mTripDetailPresenter.navigateSharePage();
        }
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = getString(R.string.trip_group_detail);
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        if (mode == FINDER_MODE) {
            if (checkStatus == ServiceInfo.STATUS_CHECHED) {
                config.mTopbarRightAreaName = getString(R.string.edit_icon);
                config.mRightStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
            }
        } else {
            config.mTopbarRightAreaName = getString(R.string.share_icon);
            config.mRightStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        }
        return config;
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mFavAnimation == null) {
            mFavAnimation = new FavAnimation(getWindow()) {
                @Override
                public int getTextResource() {
                    return R.string.fav_full_icon;
                }
            };
            mFavAnimation.attach();
        }
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void displayLoading() {

    }

    @Override
    public void displayContent() {
        mStateLayout.changeState(StateLayout.State.INIT);
    }

    @Override
    public void displayEmpty() {
        mStateLayout.changeState(StateLayout.State.Empty);
    }

    @Override
    public void displayNoNetwork() {
        mStateLayout.changeState(StateLayout.State.NoNetwork);
    }

    @Override
    public void showShare(ServiceShareObject shareObject) {
        if (shareDialogFragment != null && shareDialogFragment.isShowing()) {
            return;
        }
        shareDialogFragment = ShareDialogFragment.newInstance(shareObject, ShareChannelBuilder.TripShareChannel.TRIP_TYPE, MakeImageUtil.takeScreenShot(this));
        showDialogFragment(shareDialogFragment);

    }

    @Override
    public void renderFavValue(boolean isFav, boolean animation) {
        if (mode != FINDER_MODE) {
            if (isFav) {
                if (mFavAnimation != null && animation) {
                    mFavAnimation.show(favTextView);
                }
            }
            FavProxy.getInstance().updateFavIcon(favTextView, isFav);
        }
    }

    @Override
    public void renderServicePartInfo(ServiceInfo info, int reviewCount) {
        final TextView index = (TextView) findViewById(R.id.service_index);
        if (info != null) {
            if (mode == DEFAULT) {
                if (mode != FINDER_MODE) {
                    try {
                        //GA 统计查看详情
                        Product product = new Product()
                                .setId(info.getSid())
                                .setName(info.getName())
                                .setCategory(info.toCateString())
                                .setBrand(I118Util.getLanguageTag())
                                .setPrice(Double.parseDouble(info.getPrice()));

                        ProductAction productAction = new ProductAction(ProductAction.ACTION_DETAIL);
                        HitBuilders.ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder()
                                .addProduct(product)
                                .setProductAction(productAction);

                        Tracker t = MainApplication.getInstance().getDefaultTracker();
                        t.setScreenName("product");
                        t.send(builder.build());
                    } catch (Exception e) {

                    }

                }
            }


            List<String> picList = new ArrayList<>();
            picList.add(info.getBackPic());
            if (!ArrayUtil.isNullOrEmpty(info.getPic())) {
                if (info.getPic().get(0).equals(info.getBackPic())) {
                    picList.clear();
                }
                picList.addAll(info.getPic());
            }
            mAdapter.setData(picList);
            index.setText("1/" + mAdapter.getCount());
            mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                }

                @Override
                public void onPageSelected(int position) {
                    index.setText((position + 1) + "/" + mAdapter.getCount());
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
            mViewPager.setAdapter(mAdapter);
            String priceText = PriceProxy.getInstance().priceFormatText(info.getPriceType(), info.getShowCurrency(), info.getShowPrice());
            setViewText(R.id.trip_price, priceText);

            if (info.isDraft()) {
                mDateLayout.setmRightText(getString(R.string.value_no_set));
                mDateLayout.setRightTextColor(R.color.qiaomai_7c706e);
            } else {
                mDateLayout.setmRightText(getString(R.string.operation_view_date));
                mDateLayout.setRightColor(ResourceUtil.getThemeColor());
            }

            if (info.isOtherInstructionEmpty()) {
                mPreOrderLayout.setBottomLineStyle(ItemLayout.FULL);
                mOtherInstructionLayout.setVisibility(View.GONE);
            } else {
                mPreOrderLayout.setBottomLineStyle(ItemLayout.CONTENT);
                mOtherInstructionLayout.setmRightText(getString(R.string.operation_view_detail));
                mOtherInstructionLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TrackUtil.trackScreenName("/service/additional");
                        mTripDetailPresenter.navigateOtherNotes();
                    }
                });
            }

            setViewText(R.id.service_name, info.getName());
            if (info.getAddress().startsWith("-")) {
                subInfoAddress = info.getAddress().substring(1);
            } else {
                subInfoAddress = info.getAddress();
            }
            setViewText(R.id.service_address, subInfoAddress);
            LinearLayout tagLayout = (LinearLayout) findViewById(R.id.labelLayout);
            List<Label> labels = info.getLabelList();
            if (labels != null && labels.size() > 0) {
                tagLayout.setVisibility(View.VISIBLE);
                for (int i = 0; labels != null && i < labels.size(); i++) {
                    LabelView labelView = new LabelView(tagLayout.getContext());
                    Label label = labels.get(i);
                    labelView.setLabel(label);
                    LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    ll.rightMargin = Utils.dp2pixel(8);
                    labelView.setLayoutParams(ll);
                    tagLayout.addView(labelView);
                }
            } else {
                tagLayout.setVisibility(View.GONE);
            }
            RatingBarView ratingBar = (RatingBarView) findViewById(R.id.service_score);
            float rating = NumberUtils.parseFloat(info.getScore());

            ratingBar.setVisibility(reviewCount > 0 ? View.VISIBLE : View.GONE);
            ratingBar.setStar((int) rating, false);
            ratingBar.setClickable(false);
            String cateString = info.toCateString();
            if (!TextUtils.isEmpty(cateString)) {
                serviceTagTextView.setText(cateString);
                serviceTagTextView.setVisibility(View.VISIBLE);
            } else {
                serviceTagTextView.setVisibility(View.GONE);
            }

            mHighLightListView.setCircleColor(R.color.ganshi_ded8d7);
            mHighLightListView.setTextColor(R.color.ct_black);
            bindParaItem(mHighLightListView, info.getHighLight(), true);

            mPayIncludeListView.setCircleColor(R.color.ganshi_ded8d7);
            bindParaItem(mPayIncludeListView, info.getFeeInclude(), false);

            mPayExcludeListView.setCircleColor(R.color.ganshi_ded8d7);
            bindParaItem(mPayExcludeListView, info.getFeeExclude(), false);
            setViewText(R.id.service_content, Html.fromHtml(info.getDescptWithnoPic()));


            String text = TextProxy.getInstance().formatWithSingleAndMore(info.getServiceTime(), R.string.trip_attribute_duration_value_one, R.string.trip_attribute_duration_value_more);
            mDurationLayout.setmRightText(text);
            if (info.getMinBuyerNum() != info.getMaxbuyerNum()) {
                numLayout.setmRightText(info.getMinBuyerNum() + " - " + getString(R.string.trip_attribute_capacity_value_more, info.getMaxbuyerNum()));
            } else {
                String peopleText = TextProxy.getInstance().formatWithSingleAndMore(info.getMinBuyerNum(), R.string.trip_attribute_capacity_value_one, R.string.trip_attribute_capacity_value_more);
                numLayout.setmRightText(peopleText);
            }
            String advanceText = TextProxy.getInstance().formatWithSingleAndMore(info.getPreOrderDays(), R.string.trip_attribute_advance_value_one, R.string.trip_attribute_advance_value_more);

            mPreOrderLayout.setmRightText(advanceText);
        }
    }

    @Override
    public void renderInsiderInfo(CtUserInfo userInfo) {
        if (userInfo != null) {
            CircleImageView img = (CircleImageView) findViewById(R.id.author_img);
            ImageHelper.displayPersonImage(userInfo.getHeadPic(), img, null);
            if (userInfo.isIdentityValidated()) {
                verifiedView.setImageDrawable(ResourceManager.getDrawable(DrawableClass.VeritifiedSmallDrawable));
                verifiedView.setVisibility(View.VISIBLE);
            } else {
                verifiedView.setVisibility(View.GONE);
            }
            setViewText(R.id.author_name, userInfo.getNick());
            setViewText(R.id.author_sign, userInfo.getSign());
            setViewText(R.id.author_career, userInfo.getCareer());
            mRegisterLayout.setmRightText(
                    TimeUtil.formatTime(
                            InputTime.build(userInfo.getGmtCreated()),
                            OutputTime.getLocalInstance(OutputTime.OutputType.Type_DAY))
            );
            mIdentificationLayout.setRightTextSize(21.f);
            mIdentificationLayout.setmRightText(UserInfoProxy.getInstance().getFullBindBuilder(userInfo));
            mInterestListView.setCircleColor(R.color.ganshi_ded8d7);
            bindParaItem(mInterestListView, userInfo.getInterests(), false);


            if (!TextUtils.isEmpty(userInfo.getLanguage())) {
                languages = userInfo.getLanguage().replaceAll("/", "\n");
            }
            mLanguageListView.setCircleColor(R.color.ganshi_ded8d7);
            bindParaItem(mLanguageListView, languages, false);
        } else {
            insiderBlockView.setVisibility(View.GONE);
        }
    }

    @Override
    public void renderCommentInfo(ReviewInfo review) {
        if (review != null) {
            Integer commentCount = 0;
            try {
                commentCount = Integer.valueOf(review.getReviewNum());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (commentCount > 0) {
                findViewById(R.id.comment_block).setVisibility(View.VISIBLE);
                if (commentCount > 1) {
                    setViewText(R.id.comment_count, getString(R.string.review_attribute_number_more, Integer.valueOf(review.getReviewNum())));
                } else {
                    setViewText(R.id.comment_count, getString(R.string.review_attribute_number_one, Integer.valueOf(review.getReviewNum())));

                }
                if (review.getLastReview() != null) {
                    ImageHelper.displayPersonImage(review.getLastReview().getHeadPic(), mLastReviewerLogo, null);
                    long l = TimeUtil.parseString2Long(Utils.getMsToD(review.getLastReview().getGmtCreated()), "yyyy-MM-dd");
                    setViewText(R.id.comment_time,
                            TimeUtil.formatTime(
                                    InputTime.build(review.getLastReview().getGmtCreated()),
                                    OutputTime.getLocalInstance(OutputTime.OutputType.Type_DAY)
                            ));
                    setViewText(R.id.last_comment_author_name, review.getLastReview().getNick());
                    String content = review.getLastReview().getContent();
                    StringBuilder builder = new StringBuilder();
//                    builder.append("    ");
                    builder.append(content);
                    if (!TextUtils.isEmpty(builder)) {
                        setViewText(R.id.comment_content, builder);

                    }
                } else {
                    setViewText(R.id.comment_time, "");
                }
            } else {
                findViewById(R.id.comment_block).setVisibility(View.GONE);
            }
        } else {
            findViewById(R.id.comment_block).setVisibility(View.GONE);
            setViewText(R.id.comment_time, "");
        }
    }

    @Override
    public void renderFavInfo(FavInfo favInfo) {
        if (favInfo != null && favInfo.getBeLikedCount() != 0) {
            favLayout.setVisibility(View.VISIBLE);
            mFavCountView.setText(getString(R.string.favorite_number, favInfo.getBeLikedCount()));
            List<FavInfo.FavUserInfo> favUserInfoList = favInfo.getFavUserInfo();
            favListViewAdapter = new HolderViewAdapter(this, favUserInfoList, CircleLogoHolderView.class);
            favListView.setAdapter(favListViewAdapter);
        } else {
            favLayout.setVisibility(View.GONE);
        }

    }
}
